package com.boot.config;

import at.pollux.thymeleaf.shiro.dialect.ShiroDialect;
import com.boot.realm.MyRealm;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.mgt.RememberMeManager;
import org.apache.shiro.session.mgt.SessionManager;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.CookieRememberMeManager;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.apache.shiro.web.servlet.SimpleCookie;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.servlet.Filter;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Configuration
public class ShiroConfig {
    /**
     * Shiro内置过滤器，可以实现权限相关的拦截器
     *  常用的过滤器：
     *      anon: 无需认证（登录）可以访问
     *      authc: 必须认证才可以访问
     *      user: 如果使用rememberMe功能可以直接访问
     *      perms: 该资源必须得到资源权限才可以访问
     *      role: 该资源必须得到角色权限才可以访问
     */
    @Bean
    public ShiroFilterFactoryBean filterFactoryBean(@Autowired DefaultWebSecurityManager securityManager){
        ShiroFilterFactoryBean factoryBean = new ShiroFilterFactoryBean();
        factoryBean.setSecurityManager(securityManager);

        Map<String,String> map = new HashMap<>();
        map.put("/Captcha.jpg","anon");

        map.put("/*.js","anon");
        map.put("/doLogin","anon");
        map.put("/**","authc");

        factoryBean.setFilterChainDefinitionMap(map);

        //设置登录页面
        factoryBean.setLoginUrl("/login");
        return factoryBean;
    }

    /**
     * 创建DefaultWebSecurityManager
     */
    @Bean
    public DefaultWebSecurityManager getDefaultWebSecurityManager(@Autowired MyRealm myRealm){
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        // 关联realm
        securityManager.setRealm(myRealm);
        return securityManager;
    }

    @Bean
    public DefaultWebSessionManager sessionManager() {
        DefaultWebSessionManager sessionManager = new DefaultWebSessionManager();
        // 去掉shiro登录时url里的JSESSIONID
        sessionManager.setSessionIdUrlRewritingEnabled(false);
        return sessionManager;
    }

    /**
     * 配置ShiroDialect，用于thymeleaf和shiro标签配合使用
     */
    @Bean
    public ShiroDialect getShiroDialect(){
        return new ShiroDialect();
    }
}